﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace EntLibSample.DALCommon
{
    public class DBClient
    {
        public static string strConnectionString = string.Empty;
        public DbConnection connection { get; set; }
        public DbTransaction transaction { get; set; }

        private void EnsureConnectionIsNotNull()
        {
            if (connection == null)
            {
                connection = GetConnection();
            }
        }

        public DbConnection GetConnection()
        {
            DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
            connection = factory.CreateConnection();
            connection.ConnectionString = strConnectionString;
            return connection;
        }

        public DbCommand GetCommand()
        {
            EnsureConnectionIsNotNull();
            return connection.CreateCommand();
        }

        public DbTransaction BeginTransaction()
        {
            EnsureConnectionIsNotNull();
            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }
            transaction = connection.BeginTransaction();
            return transaction;
        }

        public void OpenConnection()
        {
            EnsureConnectionIsNotNull();
            connection.Open();
        }

        public void CloseConnection()
        {
            EnsureConnectionIsNotNull();
            if (connection.State != ConnectionState.Closed)
            {
                connection.Close();
            }
        }

        public void CommitTransaction()
        {
            if (transaction != null)
            {
                transaction.Commit();
            }
        }

        public void RollbackTransaction()
        {
            if (transaction != null)
            {
                transaction.Rollback();
            }
        }
    }
}
